package com.zhugang.week06;

/**
 * @program algorithms
 * @description: kthLargest
 * @author: chanzhugang
 * @create: 2022/07/18 12:31
 */
public class KthLargest2 {

    /**
     * 剑指offer 54 二叉搜索树的第K大节点
     *
     * @param root
     * @param k
     * @return
     */
    int count = 0;
    int result = 0;

    public int kthLargest(TreeNode root, int k) {
        // 中序遍历，升序，找第k大的数
        dfs(root, k);
        return result;
    }

    private void dfs(TreeNode root, int k) {
        if (root == null) {
            return;
        }
        dfs(root.right, k);
        if (count >= k) {
            // 提前终止递归，剪枝
            return;
        }

        count++;
        if (count == k) {
            result = root.val;
            return;
        }
        dfs(root.left, k);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}